const { baseUrl, remove } = require("../utils.js");
const camelCase = require("lodash/camelCase");
const upperFirst = require("lodash/upperFirst");
const getApi = require("./getApi");
const path = require("path");
const fs = require("fs");
module.exports = (plop) => {
  return {
    description: "更新api",
    prompts: [],
    actions: [
      (answers) => {
        return new Promise((resolve) => {
          getApi().then((res) => {
            answers.apiList = res || [];
            resolve("getApiFinished!");
          });
        });
      },
      ({ apiList }) => {
        const apiPath = path.join(baseUrl, "api/index.js");
        remove(apiPath);
        const appendTemplate = fs
          .readFileSync(path.join(baseUrl, "../templates/api/append.hbs"))
          .toString();
        const emptyTemplate = fs
          .readFileSync(path.join(baseUrl, "../templates/api/empty.hbs"))
          .toString();
        let apis = [];
        apiList.forEach(
          ({ path, method, title, description, req_body_other }) => {
            const data = {
              name: camelCase(path),
              path,
              isREMOVE: method === "DELETE",
              isPOST: method === "POST",
              isGET: method === "GET",
              params: [],
              comment: [`/**`],
            };
            data.comment.push(`* @name ${title}`);
            data.comment.push(`* @param {Object} args 入参`);
            if (req_body_other) {
              req_body_other = JSON.parse(req_body_other);
              // if (req_body_other.title !== "empty object") {

              // 	data.comment.push(`* @param {${upperFirst(req_body_other.type)}} param ${req_body_other.description || ""}`);
              // 	data.params.push("param");
              // }
              for (const paramKey in req_body_other.properties) {
                const param = req_body_other.properties[paramKey];
                data.params.push(paramKey);
                data.comment.push(
                  `* @param {${upperFirst(param.type)}} args.${paramKey} ${
                    param.description || ""
                  }`
                );
              }
            }
            if (description) {
              data.comment.push(`* @description ${description}`);
            }
            data.comment.push(`**/`);
            data.comment = data.comment.join("\n");
            // console.log(data.comment);
            data.params = data.params.join(",");
            data.paramsWithBracket = "{" + data.params + "}";
            if (data.paramsWithBracket === "{}") {
              data.paramsWithBracket = "params";
            }
            apis.push(plop.renderString(appendTemplate, data));
          }
        );
        const result = plop.renderString(emptyTemplate, {
          temp: apis.join("\n"),
        });
        fs.writeFileSync(apiPath, result);
      },
    ],
  };
};
